/* eslint-disable max-lines */
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Drawer, Message, Dialog, Tab } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import { toJS } from 'mobx';

import CcTheme from './components/CcTheme';
import BusTheme from './components/BusTheme';
import DataForm from './components/DataForm';
import EntranceConfig from './components/EntranceConfig';
import EntranceLogo from './components/EntranceLogo';

const tableId = uniqueId('tauTable-');
const { confirm } = Dialog;

const Xcx = () => {
  const [modal, setModal] = useState([]);
  const { xcxStore: store } = useStore();
  const xcxRef = useRef();

  useEffect(() => {
    return () => {
      store._orderStatus = '0';
      store.xcx = [];
    };
  }, []);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { ...searchArgs } = params.values;
    store.search = {
      ...searchArgs,
    };
  };

  // 配置包车主题
  const handleCcSettingTheme = () => {
    xcxRef.current = {};
    setModal(['ccSetting']);
  };

  // 配置巴士主题
  const handleBusSettingTheme = () => {
    xcxRef.current = {};
    setModal(['busSetting']);
  };

  // 配置入口位置
  const handleAddEntry = () => {
    xcxRef.current = {};
    setModal(['addEntry']);
  };

  // 配置入口logo
  const handleAddEntryLogo = () => {
    xcxRef.current = {};
    setModal(['addLogo']);
  };

  // 添加热门线路
  const handleAddLine = () => {
    xcxRef.current = {};
    setModal(['add']);
  };

  // 点击打开编辑
  const handleOpenEdit = (result) => {
    xcxRef.current = result;
    setModal([ENUMS.EDITNAME[store._orderStatus]]);
  };

  // 点击查看
  const handleView = (result) => {
    xcxRef.current = result;
    setModal([ENUMS.VIEWNAME[store._orderStatus]]);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 删除入口
  const handelDelete = (result) => {
    confirm({
      content: ENUMS._remove_text[store._orderStatus],
      onOk: async () => {
        try {
          await store.deleteXcx(result.id);
          Message.success({ content: t`删除成功!` });
        } catch (error) {
          Message.error({ content: t`删除失败!`, duration: 7000 });
          throw error;
        }
      },
    });
  };
  // 删除字典
  const handelDeleteItemId = (result) => {
    confirm({
      content: ENUMS._remove_text[store._orderStatus],
      onOk: async () => {
        try {
          await store.removeItemId(store._orderStatus === '5' ? 'travelPagePath' : 'entryLogo', result.itemId);
          Message.success({ content: t`删除成功!` });
        } catch (error) {
          Message.error({ content: t`删除失败!`, duration: 7000 });
          throw error;
        }
      },
    });
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 新增订单数据提交
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.create(toJS(result));
        Message.success({ content: t`入口创建成功` });
      } catch (e) {
        Message.error({ content: t`入口创建失败`, duration: 7000 });
        await store.query();
        throw e;
      }
    }
    setModal([]);
  };

  const handleCustomRequest = ({ file, onSuccess, onError }) => {
    const reader = new FileReader();
    reader.onloadend = async () => {
      try {
        await RSocket.rc({
          route: 'files.upload',
          args: {
            binary: {
              binaryId: file.uid,
              mimeType: file.type,
              filename: file.name,
            },
          },
          data: Buffer.from(reader.result),
        });
        onSuccess();
      } catch (e) {
        onError(e);
        Message.warning('上传失败');
      } finally {
        // eslint-disable-next-line no-undef
      }
    };
    reader.readAsArrayBuffer(file);
  };

  const handleCcThemeUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        // eslint-disable-next-line no-param-reassign
        result.extras = ENUMS._cc_keys.reduce((acc, { key, title }) => {
          acc[key] = {
            title,
            value: result.extras[key].value,
          };
          return acc;
        }, {});
        store.themeConfigTheme('appConfigs', toJS(result));
        Message.success({ content: t`包车主题配置成功` });
      } catch (e) {
        Message.error({ content: t`包车主题配置失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleBusThemeUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        // eslint-disable-next-line no-param-reassign
        result.extras = ENUMS._bus_keys.reduce((acc, { key, title }) => {
          acc[key] = {
            title,
            value: result.extras[key].value,
          };
          return acc;
        }, {});
        store.themeConfigTheme('appConfigs', toJS(result));
        Message.success({ content: t`巴士主题配置成功` });
      } catch (e) {
        Message.error({ content: t`巴士主题配置失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleEntranceUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        store.themeConfigTheme('travelPagePath', toJS(result));
        Message.success({ content: t`小程序入口编辑成功` });
      } catch (e) {
        Message.error({ content: t`小程序入口编辑失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleEntranceCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        store.themeConfigTheme('travelPagePath', toJS(result));
        Message.success({ content: t`小程序入口添加成功` });
      } catch (e) {
        Message.error({ content: t`小程序入口添加失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleEntranceLogoUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        _.unset(result, 'extra');
        await store.dictUpdate('entryLogo', toJS(result));
        Message.success({ content: t`入口Logo编辑成功` });
      } catch (e) {
        Message.error({ content: t`入口Logo编辑失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleEntranceLogoCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        _.unset(result, 'extra');
        await store.dictCreate('entryLogo', toJS(result));
        Message.success({ content: t`入口Logo添加成功` });
      } catch (e) {
        Message.error({ content: t`入口Logo添加失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handlePreview = (url) => {
    Dialog.show({
      title: t`预览`,
      content: <img src={url} style={{ maxWidth: '600px', width: '100%', height: '100%', objectFit: 'cover' }} />,
      footer: false,
    });
  };

  const handleOnCopy = async (r) => {
    try {
      await navigator.clipboard.writeText(r.id);
      Message.success({ content: t`id已复制！` });
    } catch (err) {
      console.error('id复制失败: ', err);
    }
  };

  const COLUMNS = {
    0: [
      { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
      column('routeName', { width: 180 }),
      column('type', {}),
      column('startMainAreaText', {}),
      column('startMinorAreasText', { width: 160 }),
      column('endMainAreaText', {}),
      column('endMinorAreasText', { width: 160 }),
      column('enable', { width: 90 }),
      column('sortWeight', {}),
      column('appType', { width: 100 }),
      column('crDate', { width: 130 }),
      {
        title: t`操作`,
        dataIndex: 'xcxNumber',
        width: 180,
        cell: (_, __, user) => (
          <>
            <Button text type="primary" onClick={() => handleOpenEdit(user, '2')}>{t`编辑`}</Button>
            <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
            <Button text type="primary" onClick={() => handleOnCopy(user)}>{t`复制ID`}</Button>
            <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
            <Button
              text
              type="primary"
              style={{ color: 'red' }}
              onClick={() => handelDelete(user)}
            >{t`删除`}
            </Button>
          </>
        ),
      },
    ],
    1: [
      { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
      column('routeName', {}),
      column('type', {}),
      column('startMainAreaText', {}),
      column('startMinorAreasText', { width: 180 }),
      column('endMainAreaText', {}),
      column('endMinorAreasText', { width: 180 }),
      column('enable', { width: 90 }),
      column('sortWeight', {}),
      column('appType', { width: 100 }),
      column('crDate', { width: 130 }),
      {
        title: t`操作`,
        dataIndex: 'xcxNumber',
        width: 180,
        cell: (_, __, user) => (
          <>
            <Button text type="primary" onClick={() => handleOpenEdit(user, '2')}>{t`编辑`}</Button>
            <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
            <Button text type="primary" onClick={() => handleOnCopy(user)}>{t`复制ID`}</Button>
            <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
            <Button
              text
              type="primary"
              style={{ color: 'red' }}
              onClick={() => handelDelete(user)}
            >{t`删除`}
            </Button>
          </>
        ),
      },
    ],
    2: [
      { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
      column('routeName', {}),
      column('enable', { width: 90 }),
      column('sortWeight', {}),
      column('appType', { width: 100 }),
      column('crDate', { width: 130 }),
      {
        title: t`操作`,
        dataIndex: 'xcxNumber',
        width: 180,
        cell: (_, __, user) => (
          <>
            <Button text type="primary" onClick={() => handleOpenEdit(user, '2')}>{t`编辑`}</Button>
            <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
            <Button text type="primary" onClick={() => handleOnCopy(user)}>{t`复制ID`}</Button>
            <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
            <Button
              text
              type="primary"
              style={{ color: 'red' }}
              onClick={() => handelDelete(user)}
            >{t`删除`}
            </Button>
          </>
        ),
      },
    ],
    3: [
      { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
      column('routeName', {}),
      column('type', {}),
      column('startMainAreaText', {}),
      column('startMinorAreasText', { width: 180 }),
      column('endMainAreaText', {}),
      column('endMinorAreasText', { width: 180 }),
      column('enable', { width: 90 }),
      column('sortWeight', {}),
      column('appType', { width: 100 }),
      column('crDate', { width: 130 }),
      {
        title: t`操作`,
        dataIndex: 'xcxNumber',
        width: 180,
        cell: (_, __, user) => (
          <>
            <Button text type="primary" onClick={() => handleOpenEdit(user, '2')}>{t`编辑`}</Button>
            <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
            <Button text type="primary" onClick={() => handleOnCopy(user)}>{t`复制ID`}</Button>
            <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
            <Button
              text
              type="primary"
              style={{ color: 'red' }}
              onClick={() => handelDelete(user)}
            >{t`删除`}
            </Button>
          </>
        ),
      },
    ],
    5: [
      { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
      column('itemId', {
        cell: (v, i, r) => <Button text type="primary" onClick={() => handleView(r)}>{v}</Button>,
      }),
      column('name', {}),
      column('sortWeight', {}),
      column('disabled', {}),
      {
        title: t`操作`,
        dataIndex: 'Number',
        width: 180,
        cell: (_, __, xcx) => (
          <>
            <Button text type="primary" onClick={() => handleOpenEdit(xcx, '1')}>{t`编辑`}</Button>
            <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
            <Button text type="primary" style={{ color: 'red' }} onClick={() => handelDeleteItemId(xcx, '1')}>{t`删除`}</Button>
          </>
        ),
      },
    ],
    6: [
      { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
      column('extras', {
        cell: (v) => {
          const { image } = v;
          const parseValue = JSON.parse(image?.value);
          const { baseUrl } = global.getEnvCfg();
          const url = `${baseUrl}/api/files/${parseValue[0]?.uid}`;
          return (
            <img style={{ width: 100 }} src={url} onClick={() => handlePreview(url)} />
          );
        },
      }),
      column('itemId', {
        cell: (v, i, r) => <Button text type="primary" onClick={() => handleView(r)}>{v}</Button>,
      }),
      column('name', {}),
      column('sortWeight', {}),
      column('disabled', {}),
      {
        title: t`操作`,
        dataIndex: 'Number',
        width: 180,
        cell: (_, __, xcx) => (
          <>
            <Button text type="primary" onClick={() => handleOpenEdit(xcx, '1')}>{t`编辑`}</Button>
            <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
            <Button text type="primary" style={{ color: 'red' }} onClick={() => handelDeleteItemId(xcx, '1')}>{t`删除`}</Button>
          </>
        ),
      },
    ],
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-addHotLine',
            title: t`入口配置`,
            type: 'primary',
            onClick: handleAddLine,
          },
          {
            name: 'btn-ccSettingTheme',
            title: t`包车主题配置`,
            type: 'primary',
            onClick: handleCcSettingTheme,
          },
          {
            name: 'btn-busSettingTheme',
            title: t`巴士主题配置`,
            type: 'primary',
            onClick: handleBusSettingTheme,
          },
          {
            name: 'btn-addEntry',
            title: t`添加入口位置`,
            type: 'primary',
            onClick: handleAddEntry,
          },
          {
            name: 'btn-addEntryLogo',
            title: t`添加入口logo`,
            type: 'primary',
            onClick: handleAddEntryLogo,
          },
        ]}
        searchItems={[
          {
            name: 'type',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.type),
              placeholder: '线路类型',
              style: { width: 120 },
            },
          },
          {
            name: 'subType',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.subType),
              placeholder: '副业类型',
              style: { width: 160 },
            },
          },
        ]}
        keywordSearch={{
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <Tab
          activeKey={store.orderStatus}
          onChange={(v) => {
            store.xcx = [];
            store.orderStatus = v;
          }}
        >
          {ENUMS.tabItems.map((item) => (
            <Tab.Item key={item.key} title={item.label} />
          ))}
        </Tab>
        <TauTable
          instanceId={tableId}
          primaryKey="itemId"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={toJS(store.total)}
          onFetch={(pg) => {
            store.pg = pg;
          }}
          loading={store.loading}
          dataSource={toJS(store.xcx)}
          columns={COLUMNS[store._orderStatus]}
        />
      </div>
      <Drawer
        visible={modal[0] === 'ccSetting'}
        title={t`包车主题配置`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="100%"
      >
        <CcTheme
          userInfo={xcxRef.current}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={handleCcThemeUpdate}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'busSetting'}
        title={t`巴士主题配置`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="100%"
      >
        <BusTheme
          userInfo={xcxRef.current}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={handleBusThemeUpdate}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'entrance' || modal[0] === 'addEntry' || modal[0] === 'viewEntrance'}
        title={t`入口配置`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="600px"
      >
        <EntranceConfig
          dictInfo={xcxRef.current}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'entrance' ? handleEntranceUpdate : handleEntranceCreate}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'logo' || modal[0] === 'addLogo' || modal[0] === 'viewLogo'}
        title={modal[0] === 'logo' ? t`添加入口Logo` : t`编辑入口Logo`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="600px"
      >
        <EntranceLogo
          dictInfo={xcxRef.current}
          modal={modal}
          onCancel={handleCancel}
          handleCustomRequest={handleCustomRequest}
          onSubmit={modal[0] === 'logo' ? handleEntranceLogoUpdate : handleEntranceLogoCreate}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'add' || modal[0] === 'edit'}
        title={modal[0] === 'add' ? t`添加小程序入口` : t`修改小程序入口`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="85%"
      >
        <DataForm
          xcxInfo={xcxRef.current}
          modal={modal}
          onCancel={handleCancel}
          handleCustomRequest={handleCustomRequest}
          onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>

    </TauPage>
  );
};

export default observer(Xcx);
